package com.auto.api.core.type.json.yapi;

import com.auto.api.common.utils.JsonMapper;
import com.auto.api.core.type.TypeFactory;
import com.auto.api.core.type.defaultvalue.ValueTypeHandler;
import com.auto.api.core.util.BeanUtil;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Map;
import org.springframework.core.ResolvableType;

/**
 * @program:
 * @description: CollectionJsonTypeHandler类型处理器
 * @author: liangshf
 * @create: 2020-09-24
 */
public class CollectionJsonTypeHandler extends AbstractResultJsonTypeHandler {

    @Override
    public boolean canCovert(ResolvableType resolvableType) {
        return resolvableType.isArray();
    }

    @Override
    public String getResultJson(ResolvableType resolvableType, Map resultMap){
        List list = Lists.newArrayList();
        if (resolvableType.hasGenerics()) {
            ResolvableType genType = resolvableType.getGenerics()[0];
            Class rowClass = genType.getRawClass() == null ? String.class : genType.getRawClass();
            ValueTypeHandler typeHandler = TypeFactory.getTypeHandler(rowClass.getSimpleName());
            if (typeHandler != null) {
                list.add(typeHandler.getTypeDefaultValue());
                resultMap.put(resolvableType.resolve().getSimpleName(), list);
                return JsonMapper.toJson(resultMap);
            }
            resultMap.put(resolvableType.resolve().getSimpleName(), list.add(BeanUtil.getClassColumnMap(genType)));
        } else {
            list.add(TypeFactory.getTypeHandler(String.class.getSimpleName()).getTypeDefaultValue());
            resultMap.put(resolvableType.resolve().getSimpleName(), list);
        }
        return JsonMapper.toJson(resultMap);
    }
}